<?php


namespace App\Http\observer;


use App\Engine\BaseCommon;
use App\Exceptions\ApiException;
use App\Models\Custom;
use App\Models\Image;
use App\Models\Sys;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CustomObserver
{


    public function saving(Custom $custom)
    {
        $user=User::where("id",$custom->uid)->first();
        if (!$user){
            throw new ApiException("用户不存在");
        }
    }

    public function updating(Custom $custom)
    {
        $old_custom=Custom::where("id",$custom["id"])->first();
        if($old_custom["qrcode"]){
            Cache::put("custom_qrcode",$old_custom["qrcode"]);
        }
        if ($old_custom["header"]){
            Cache::put("custom_header",$old_custom["header"]);
        }

        $qedit=(new BaseCommon())->getImgs($old_custom["content"],0);
        if ($qedit){
            Cache::put("custom_content",$qedit);
        }
    }

    public function updated(Custom $custom)
    {
        $custom_qrcode=Cache::get("custom_qrcode");
        $custom_header=Cache::get("custom_header");
        $custom_content=Cache::get("custom_content");
        Cache::forget("custom_qrcode");
        Cache::forget("custom_header");
        Cache::forget("custom_content");
        if ($custom_qrcode&&$custom_qrcode!=$custom->qrcode){
            Image::del_data($custom_qrcode);
        }
        if ($custom_header&&$custom_header!=$custom["header"]){
            Image::del_data($custom_header);
        }
        $content=(new BaseCommon())->getImgs($custom->content);
        if ($content&&$custom_content&&$custom_content!=$content){
            $oss_address=Sys::getValue("oss_address");
            $url=str_replace($oss_address,"",$custom_content);
            Image::del_data($url);
        }

    }

    public function deleted(Custom $custom)
    {
        if($custom->qrcode){
            Image::del_data($custom->qrcode);
        }
        if ($custom["header"]){
            Image::del_data($custom["header"]);
        }
        $oss_address=Sys::getValue("oss_address");
        $qedit=(new BaseCommon())->getImgs($custom->content);
        if ($qedit){
            $qedit=str_replace($oss_address,"",$qedit);
            if ($qedit){
                Image::del_data($qedit);
            }
        }
    }
}
